<?php

namespace Fun\Parse\Controller;

use Al\Core\Lib\Controller,
    Al\Core\Lib\DOM\Query,
    Al\Core\Lib\Service;

class ParserController extends Controller {

  public function mainAction($path, $name) {
    $query = new Query(file_get_contents(base64_decode($path)));
    $location = $query('img[name="thiskep"]')->get(0)
      ->getAttribute('src');
    $fname = $query('#mykep_name center a')->get(0)
      ->getAttribute('title');
    $matches = array();
    preg_match('/[^\d]+/', $fname, $matches);
    if (!is_file($file = ($folder = "/home/al/Downloads/$name/" .
        trim($matches[0])) . "/$fname")) {
      @mkdir($folder, 0777, true);
      $file = rtrim($file, '.');
      $ext = pathinfo($file, PATHINFO_EXTENSION);
      if (!Service::get("mime.type.$ext")) {
        $finfo = new \finfo(FILEINFO_MIME);
        $mime = explode(';', $finfo->file($location));
        $ext = Service::get("mime.ext.$mime[0]");
        $file .= '.' . $ext;
        $fname = rtrim($fname, '.') . '.' . $ext;
      }
      file_put_contents($file, fopen($location, 'r'));
    }
    return $this->render('Fun\Parse::parse.html.smarty', array(
      'url' => Service::get('request')->buildRoutePath('parse', array(
        'path' => base64_encode('http://xfree.hu/' .
          $query('body>center>table>tr>td>table>tr>td>a')->get(4)
          ->getAttribute('href')))),
      'name' => $fname,
    ));
  }

  public function launchFormAction() {
    return $this->render('Fun\Parse::launch.html.smarty');
  }

  public function launchAction() {
    $post = Service::get('http.post');
    Service::get('request')->redirect('parse', array(
      'name' => trim($post['name']),
      'path' => base64_encode($post['path']),
    ));
  }

}